//
//  NewHomeWebViewController.m
//  HCNewGoldFinger
//
//  Created by 刘琛 on 2017/6/13.
//  Copyright © 2017年 zjhcsoftios. All rights reserved.
//

#import "NewHomeWebViewController.h"
#import "ZPHCNewReassignPeopleListViewController.h"
#import "ZSBStatusInfo.h"
#import "NewOrderDetailViewController.h"
#import "UIViewController+BackButtonHandler.h"
#import <WebViewJavascriptBridge/WebViewJavascriptBridge.h>
#import <Masonry/Masonry.h>
#import "ISeeUserInfoModel.h"
#import "NetworkAddress.h"
#import <MJExtension/MJExtension.h>
#import "NSString+EX.h"


@interface NewHomeWebViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *web;

@property WebViewJavascriptBridge* bridge;

@property (nonatomic, strong) NSString *loadUrl;

@end

@implementation NewHomeWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    _web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - Height_NavBar)];
    _web.delegate = self;
    [self.view addSubview:_web];
    
    [_web mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
        } else {
            make.edges.mas_equalTo(self.view);
        }
    }];
    
    [self createWebBridge];
    
    ISeeUserInfoModel *userInfo = [ISeeUserInfoModel mj_objectWithKeyValues:[[[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserInfo] mj_JSONObject]];
    
    _loadUrl = [NSString stringWithFormat:@"http://qxisee.zjtelecom.com.cn:9090/mcs/nmarket/mybill/mobile/validateUserPage.html?userId=%@&random=5554&slType=1",userInfo.userId];
    
    [_web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_loadUrl]]];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"%@", self.web.request.URL.absoluteString);
    if ([self.web.request.URL.absoluteString rangeOfString:@"businessBill"].location != NSNotFound && self.web.request.URL.absoluteString) {
        NSString *json = [[NSUserDefaults standardUserDefaults] objectForKey:@"ShangJiShuaiDan"];
        
        [self.web stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getTurnSendResult('%@')", json]];
        
//        [self.web stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getTurnSendResult()"]];
    }}

- (void)createWebBridge
{
    [WebViewJavascriptBridge enableLogging];
    
    _bridge = [WebViewJavascriptBridge bridgeForWebView:_web];
    
//    _bridge = [WebViewJavascriptBridge bridgeForWebView:_web webViewDelegate:self handler:^(id data, WVJBResponseCallback responseCallback) {
//        NSLog(@"ObjC received message from JS: %@", data);
//        responseCallback(@"Response for message from ObjC");
//    }];
    
    [_bridge registerHandler:@"turnSend" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
//        [self xiaoshouzhushou:data];
        [self goNext];
    }];
//    
    [_bridge registerHandler:@"toValidateUserApp" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        [self xiaoshouzhushou:data];
    }];
    
}

-(void)xiaoshouzhushou:(NSString *) jsonStr{
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"zqhelper://"]]) {
        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                             
                                                            options:NSJSONReadingMutableContainers
                             
                                                              error:&err];
        
        
        
        NSString *str = [NSString stringWithFormat:@"zqhelper://iseetb&loginCode=%@&cityId=%@&cityName=%@&crmLoginId=%@",dic[@"loginCode"],dic[@"cityId"], [NSString URLEncodedString:dic[@"cityName"]],dic[@"crmLoginId"]];
        NSLog(@"%@",str);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        
    }else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://mobile.zjhcsoft.com:8002/files/63/2.8.8/index.html"]];
    }
}





- (void)goNext {
    
    ZPHCNewReassignPeopleListViewController * viewCtrl = [[ZPHCNewReassignPeopleListViewController alloc] init];
    //        viewCtrl.billIds = [self allSelectIds];
    viewCtrl.shaidan = YES;
    [self.navigationController pushViewController:viewCtrl animated:YES];

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    
    NSString *query = request.URL.query;
    if (query && [query rangeOfString:@"tradeOrderNum"].location != NSNotFound) {
        NSArray *array = [query componentsSeparatedByString:@"="];
        if (array.count>1) {
            NSString *tradeOrderNum = array[1];

            ZSBStatusInfo *statusInfo = [[ZSBStatusInfo alloc] init];
            statusInfo.tradeOrderNum = tradeOrderNum;
            statusInfo.type = 1;

            NewOrderDetailViewController *viewCtrl = [[UIStoryboard storyboardWithName:@"ZPaiyingxiao" bundle:nil] instantiateViewControllerWithIdentifier:@"NewOrderDetailViewController"];;
            viewCtrl.statusInfo =statusInfo;

            viewCtrl.title = @"订单流程";
            [self.navigationController pushViewController:viewCtrl animated:YES];
            
            return NO;
        }
    }
    return YES;
}

- (BOOL)navigationShouldPopOnBackButton {

        return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
